package com.gwtprocessingjs.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * This class demonstrates pulling data into GWT from code
 * written in the Processing scripting language.
 */
public class GwtFromPde implements EntryPoint {
	
	// UI Elements.
	private final FlowPanel back = new FlowPanel();
	private final Label positionLabel = new Label("Click to get the position of the ball.");
	private final Button getPositionButton = new Button("Get Position");
	
	@Override
	public void onModuleLoad() {
		back.add(new Label("Updating GWT based on data pulled from a pde script"));	
		HorizontalPanel hp = new HorizontalPanel();
		hp.add(getPositionButton);
		hp.add(positionLabel);
		back.add(hp);
		RootPanel.get("gwt").add(back);
		
		getPositionButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				positionLabel.setText("The position is: " + getPosition());
			}
		});
	}
	
	// --- Private Methods ---
	
	/**
	 * @return the position of the ball, computed by the
	 * getPosition function in the associated pde script.
	 */
	private native String getPosition() /*-{
		
		// "GwtFromPde" is the id of the canvas element created in the
		// HTML file.
		var myProcessing = $wnd.Processing.getInstanceById('GwtFromPde');
		return myProcessing.getPosition();
	}-*/;
}
